// mircoApp/groupPurchase/purchaseDetails/purchaseDetails.js
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Hei:0,
    imgheights:[], //自适应轮播图参数
    imgBoxSize:'',
    purchaseTime:'',
    presentTime:'',
    timeData: {},
    goodsId:'',
    posterShow:false,
    popupSpecs:false,
    showKefu:false,
    getGoods:{}, //商品详情数据
    optionsObj:{},
    language:'',
    plugin:{}, //插件数据
    goodsTag:'', //立即购买是1，加入购物车是2
    goodsCount:'',
    optionsId:'',
    customer_open:'',
    cservice:'',
    service_QRcode:'',
    service_mobile:'',
    bottomButton:'',
    activeFlag:'', //活动未开始显示原价
    imgPath: app.globalData.imgPath, //显示图片
    purInfo:{
      over_top:"455",
      icon_url:`${app.globalData.imgPath}/bc_eweima.png`
    },
    style:{
      headBg:''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.presentTime = new Date().getTime();
    if(options.id) {
      this.setData({
        goodsId: Number(options.id),
      })
    }
    if (options.scene) { //海报参数
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "id") {
            //解决场景：海报带参后字符长度超出，将参数值直接与id合并，通过 / 分割，第一个需为id,其他自定义
            let paramsID = chil_arr[1].split("/");
            console.log(paramsID);
            this.setData({
              goodsId: paramsID[0],
            });
          }else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          } else {
            this.goodsdetails();
          }
        }
      }
    } else {
      if (options.mid) {
        app._setMid(options.mid);
        this.shareNum();
      }
    }
    this.styleFun();
    this.goodsdetails();
  },
  styleFun() {
    this.setData({
      ['style.headBg']:` background-image: url(${this.data.imgPath}yz-group-buy-activity/group-head.png)`,
    })
  },
  //返回上一页
  onBack() {
    const pages = getCurrentPages();
    if(pages.length === 1) {
      wx.navigateTo({ url:'/packageG/index/index'})										
    } else {
      wx.navigateBack({ delta: 1 })
    }
  },
  onService() {
    this.setData({
      showKefu:true
    })
  },
  posterClick() {
    this.setData({
      posterShow:true
    })
  },
  previewImg(e){
    let ind;
    ind = e.currentTarget.dataset.key;
    wx.previewImage({
      current: ind?this.data.getGoods.thumb_url[ind]:this.data.getGoods.thumb_url, // 当前显示图片的http链接
      urls: this.data.getGoods.thumb_url // 需要预览的图片http链接列表
    });
  },
  //规格事件
  close_yz_specs_popup(event) {
    this.setData({
      popupSpecs: false,
    });
  },
  selectSpecsOn(event) {
    let {clicktype,goodsCount,optionsId} = event.detail;
    if (clicktype  == 1) {
      this.setData({
        goodsCount,
        optionsId
      })
    }
  },
  submitAction(event) {
    let {tag} = event.currentTarget.dataset;
    if (this.data.goodsCount <= 0) {
      wx.showToast({
        icon: 'none',
        title: '商品库存不足',
        duration: 1500
      });
      return;
    }
    if(tag == 2) {
      this.addCartReq(this.data.goodsId,this.data.optionsId,this.data.goodsCount); //添加购物车
    }else {
        //点击确认按钮
      let url = '/packageD/buy/myOrder_v2/myOrder_v2?tag=-2';
      let _urlParam = `&goodsId=${this.data.goodsId}&optionsId=${this.data.optionsId}&total=${this.data.goodsCount}`;
      wx.navigateTo({
        url: url + _urlParam
      });
    }
    
    this.setData({
      popupSpecs: false,
    });
  },
  //商品详情数据
  goodsdetails() {
    let query = {
      id: this.data.goodsId,
      basic_info:1
    };
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: query,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let getGoods= res.data.get_goods;
          let bottomButton = res.data.bottom_button;
          getGoods.content = getGoods?.content.replace(/<img/g, '<img style="max-width:100%;height:auto;"');
          let plugin = res.data?.plugin?.yz_group_buy_activity;
          let plugin_setting = res.basic_info?.plugin_setting;
          let actTime = '';
          let activeFlag = '';
          if(!plugin.active) {
            wx.redirectTo({
              url:`/packageA/detail_v2/detail_v2?id=${this.data.goodsId}`
            })
          }
          if(this.data.presentTime < (plugin.time_start * 1000)) { //活动未开始，按原价购买,显示为开始的时间
            activeFlag = 1;
            actTime = (plugin.time_start * 1000) - this.data.presentTime;
          } else {
            actTime = (plugin.time_end * 1000) - this.data.presentTime;
          }
          this.setData({
            getGoods: getGoods,
            bottomButton:bottomButton,
            plugin:plugin,
            activeFlag:activeFlag,
            pluginSetting: plugin_setting,
            purchaseTime:actTime,
            optionsObj:getGoods.has_many_options[0],
            customer_open: res.data.customer_service?.customer_open == "1" ? true : false,
            cservice: res.data.customer_service?.cservice,
            service_QRcode: res.data.customer_service?.service_QRcode,
            service_mobile: res.data.customer_service?.service_mobile,
          })
        } else {
          wx.showModal({
            content: res.msg,
            success (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  shareNum() { //只调用接口，不做任何操作
    let url = app.getNetAddresss("plugin.yz-group-buy-activity.api.index.share");
    app._getNetWork({
      url,
      data:{
        id: this.data.goodsId,
      },
      success: (resdata) => {
        let res = resdata.data;
      },
      fail: function (res) {
        console.log(res);
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 2500,
        });
      }
    });
  },
  gotoHome() {
    wx.reLaunch({
      url: "/packageG/index/index",
    });
  },
  buyNow(){
    let urlStr = app.getNetAddresss("member.member.isValidatePageGoods");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              popupSpecs:true,
              goodsTag:1,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
  },
  //子组件事件
  onCopy(e) {
    let {text} = e.detail;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              icon: "none",
              title: '复制成功!',
              duration: 1500,
            });
          }
        })
      }
    })
  },
  //添加到购物车
  addCart(event) {
    let that = this;
    let urlStr = app.getNetAddresss("member.member.isValidatePageGoods");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success:  (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              popupSpecs:true,
              goodsTag:2,
            })
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
  },
  addCartReq(_goodsId, _optionsId, _total) {
    
    // let that = this;
    let urlStr = app.getNetAddresss("member.member-cart.store");
    urlStr += "&goods_id=" + _goodsId;
    urlStr += "&total=" + _total;
    urlStr += "&option_id=" + _optionsId;
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          app.globalData.cart_num = res.data.cart_num;
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 2500,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success (res) {}
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  imgH(e){
    var winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    var imgh=e.detail.height;//图片高度
    var imgw=e.detail.width;
    var swiperH=winWid*imgh/imgw;　//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.data.imgheights.push(swiperH);
    this.data.imgBoxSize = Math.max.apply(null, this.data.imgheights);
    this.setData({
        Hei:`${this.data.imgBoxSize}px`//设置高度
    })
  },
  purChange(event) {
    this.setData({
      timeData: event.detail,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/mircoApp/groupPurchase/purchaseDetails/purchaseDetails?id=" + this.data.goodsId + "&mid=" + mid,
      title: this.data.plugin.share_text,
      imageUrl: this.data.getGoods.thumb
    };
    
  },
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      query: "/mircoApp/groupPurchase/purchaseDetails/purchaseDetails?id=" + this.data.goodsId + "&mid=" + mid,
      title: this.data.plugin.share_text,
      imageUrl: this.data.getGoods.thumb
    };
  }
  
})